package com.wskeee.ec.components
{
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.utils.Dictionary;
	
	[Event(name="change", type="flash.events.Event")]
	
	public class RadioButtonGroup extends EventDispatcher
	{
		private var buttons:Vector.<RadioButton> = new Vector.<RadioButton>();
		private var currentRadioButton:RadioButton;
		private var _name:String;
		
		public function RadioButtonGroup(groupName:String)
		{
			super();
			_name = groupName;
			groups[name] = this;
		}
		
		//========================= static ======================
		private static var groups:Dictionary = new Dictionary();

		public static function getGroup(name:String):RadioButtonGroup
		{
			if(!groups[name])
				groups[name] = new RadioButtonGroup(name);
			return groups[name];
		}
		//========================= end =========================
		
		//========================= act =========================
		/**
		 * 添加 不定数目的 radioButton 到组里 
		 * @param arug
		 * 
		 */
		public function adds(...arug):void
		{
			for(var i:int=0,len:int=arug.length;i<len;i++)
				add(arug[i] as RadioButton);
		}
		/**
		 * 添加一个 radioButton 到组里 
		 * @param value
		 * 
		 */
		public function add(value:RadioButton):void
		{
			if(!contains(value))
			{
				value.addEventListener(Event.CHANGE, onRadioButtonChange);
				buttons.push(value);
			}
		}
		
		protected function onRadioButtonChange(event:Event):void
		{
			var rb:RadioButton = event.target as RadioButton;
			if(rb != currentRadioButton)
			{
				if(currentRadioButton)
				currentRadioButton.selected = false;
				currentRadioButton = rb;
				currentRadioButton.selected = true;
				dispatchEvent(new Event(Event.CHANGE));
			}
		}
		/**
		 * 删除一个 radioButton 按钮 
		 * @param value
		 * 
		 */
		public function remove(value:RadioButton):void
		{
			if(contains(value))
			{
				value.removeEventListener(Event.CHANGE, onRadioButtonChange);
				buttons.splice(buttons.indexOf(value),1);
				if(currentRadioButton == value)
				{
					currentRadioButton = null;
					dispatchEvent(new Event(Event.CHANGE));
				}
			}
		}
		
		public function contains(value:RadioButton):Boolean
		{
			return buttons.indexOf(value)!=-1;
		}
		
		/**
		 * 销毁组 
		 * 
		 */
		public function destory():void
		{
			while(buttons.length>0)
				remove(buttons[0]);
			delete groups[name];
		}
		
		/**
		 * 当前组选择的值 
		 * @return 
		 * 
		 */
		public function get value():Object
		{
			return currentRadioButton ? currentRadioButton.value : null;
		}
		
		public function get name():String
		{
			return _name;
		}
		//========================= end =========================
	}
}